<?php

namespace App\B2BProject;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\Exception\FileException;

/**
 * Class AttachmentTempFiles
 *
 * 临时附件模型，用于某些上传预览，且文件有保密要求的时候
 *
 * @package App\B2BProject
 */
class AttachmentTempFiles extends Model
{
    protected $fillable
        = [
            'sha512',
            'extension',
            'local_path',
            'mime_type',
            'original_name',
            'size',
            'expire',
            'token',
        ];

    public static function setNewUploadFile(UploadedFile $file, $path = '')
    {
        if ($file->isValid()) {
            $sha512    = hash_file('sha512', $file->getPathname());
            $extension = $file->guessClientExtension();
            $localName = md5($sha512) . '_' . time() . '.' . $extension;
            $mime      = $file->getMimeType();
            $origin    = $file->getClientOriginalName();
            $size      = $file->getSize();

            $target = trim(str_replace(base_path(), '',
                $file->move(base_path('storage/app/upload/temp_attachment' . $path), $localName)), '\/');

            $new                = new static;
            $new->sha512        = $sha512;
            $new->mime_type     = $mime;
            $new->local_path    = $target;
            $new->extension     = $extension;
            $new->original_name = $origin;
            $new->size          = $size;
            $new->token         = Str::random(60);
            $new->expire        = date('Y-m-d H:i:s', time() + 900);

            $new->save();

            return $new;
        } else {
            throw new FileException('Upload error');
        }
    }

    public static function getFileByToken($token)
    {
        return self::where('token', $token)->where('expire', '>', date('Y-m-d H:i:s', time()))->firstOrFail();
    }
}
